package org.jash.day7;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import org.jash.day7.entity.DataBean;
import org.jash.day7.entity.DataBeanDao;

import java.util.ArrayList;
import java.util.List;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
    private final DataBeanDao dao;
    private List<DataBean> data = new ArrayList<>();

    public NewsAdapter() {
        dao = App.getSession().getDataBeanDao();
    }

    @NonNull
    @Override
    public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new NewsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) {
        final DataBean dataBean = data.get(position);
        holder.title.setText(dataBean.getTitle());
        Glide.with(holder.icon)
                .load(dataBean.getImgurl())
                .into(holder.icon);
        holder.itemView.setOnLongClickListener(v ->{
            int p = data.indexOf(dataBean);
            data.remove(p);
            notifyItemRemoved(p);
            return true;
        });
        DataBean bean = dao.load(dataBean.getId());

        holder.favorite.setChecked(bean != null);
        holder.favorite.setOnCheckedChangeListener((box, isChecked) -> {
            if (isChecked) {
                dao.insert(dataBean);
            } else {
                dao.delete(dataBean);
            }

        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    public void addAll(List<DataBean> list) {
        int size = data.size();
        data.addAll(list);
        notifyItemRangeInserted(size, list.size());
    }

    public static class NewsViewHolder extends RecyclerView.ViewHolder {
        private ImageView icon;
        private TextView title;
        private CheckBox favorite;
        public NewsViewHolder(@NonNull View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.icon);
            title = itemView.findViewById(R.id.title);
            favorite = itemView.findViewById(R.id.favorite);
        }
    }
}
